//引入 fly
var Fly = require("flyio/dist/npm/wx");
const fly = new Fly();
const { version } = require('../package.json');
import { store, mutations } from "../store/index";
import config from '../utils/config';
import { SM4 } from "../utils/crypto.js";

import {
	getStore,
	toast,
	clearStore
} from '../utils/index'
import {
	showLoading,
	hideLoading
} from '../utils/loading';
const accessAuth = SM4()
var whiteList = ['login', 'reg', 'forgetPassword', 'getDetail', 'index'] //getDetail是注册获取协议接口
function getToken(request) {

	let token = getStore('token');
	let route = getCurrentPages()[0].route;
	let url = route.split('/')[1];
	if (whiteList.indexOf(url) != -1) {
		return token
	} else {
		if (token) {
			return token
		} else {
			const tokenStatus = false;
			store.commit('setToken', tokenStatus);
			console.log(store.state.isToken, "这里是否能拿到值");
			uni.showModal({
				title: '提示',
				content: '为了更好的为您服务，请登录',
				success: function(res) {
					if (res.confirm) {
						clearStore()
						uni.navigateTo({
							url: '/My/oneClicklogin/login'
						})
					} else if (res.cancel) {
						console.log('用户点击取消');
					}
				}
			});
		}
	}
}

fly.config.timeout = 100000;
fly.config.baseURL = config.host;
// 请求拦截器，判断某些请求是否需要携带 token
fly.interceptors.request.use((request) => {
	if (request.requiresToken) {
		const token = getToken(request);

		if (token) {
			request.headers["X-Access-Token"] = token;
		} else {
			console.warn("Token 不存在");
		}
	}
	return request;
}, (error) => {
	return Promise.reject(error);
});

fly.interceptors.request.use((request) => {
	showLoading();
	request.headers['Content-Type'] = 'application/json;charset=UTF-8'
	request.headers["Authorization"] = "Bearer " + getStore('token');
	request.headers["operator-token"] = getStore('operator_token');
	request.headers["Clientid"] = '4307744c840008aa4c1e23d5edcd9461';
	request.headers["terminal-version"] = version;
	request.headers["terminal-type"] = 'mini';
	request.headers["X-Access-Auth"] = accessAuth;
	// toast();
	return Promise.resolve(request);
}, (error) => {
	return Promise.reject(error);

});
fly.interceptors.response.use((response) => {

		hideLoading();
		let result = response.data;
		if (result.code == 200) {
			return Promise.resolve(response.data);
		} else if (result.code == '401' && result.msg == '认证失败，无法访问系统资源') {

			const tokenStatus = false;
			store.commit('setToken', false);
			console.log(store.state.isToken, "这里是否能拿到值");
			uni.showModal({
				title: '提示',
				content: '为了更好的为您服务，请登录后访问',
				success: function(res) {
					if (res.confirm) {
						clearStore()
						uni.navigateTo({
							url: '/My/oneClicklogin/login'
						})
					} else if (res.cancel) {
						let data = getCurrentPages();
						if (data.length > 1) {
							uni.navigateBack({
								data: 1
							})
						} else {
							return
						}
					}
				}
			});
		} else {
			// toast(result.message);
			return Promise.resolve(response.data);
		}
	},
	(err) => {
		console.log(err, 'err');

		let { response: { code, data: { msg } } } = err;
		hideLoading();

		switch (code) {
			case 403:
				toast("拒绝访问");
				break;
			case 500:

				if (msg === "认证失败，无法访问系统资源" || msge === "token失效" || msg === "token不能为空") {
					toast("很抱歉，登录已过期，请重新登录");
					uni.clearStorage();
					const tokenStatus = false;
					store.commit('setToken', false);
					console.log(store.state.isToken, "这里是否能拿到值");
					// store.dispatch("logout")
					// 这里这一步保留,之后用
					// setTimeout(() => {
					//     uni.navigateTo({
					//         url: '/My/oneClicklogin/login'
					//     })
					// }, 1500);
				} else {
					toast("服务器内部错误");
				}
				break;

			case 404:
				toast("很抱歉，资源未找到!");
				break;
			case 504:
				toast("网络超时!");
				break;
			case 401:
				toast("未授权，请重新登录!");
				break;
			default:
				toast(msg);
				break;
		}
	}
);
export default fly